package hr.web.jsf;

import java.util.Iterator;
import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.component.UISelectOne;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

public class JSFUtils {
	public static UIComponent findComponent(final UIComponent component,
			final String id) {
		if (component.getId().equals(id)) {
			return component;
		} else {
			final List<UIComponent> children = component.getChildren();
			for (final UIComponent myComponent : children) {
				final UIComponent componentFound = findComponent(myComponent,
						id);
				if (componentFound != null) {
					return componentFound;
				}
			}
			return null;
		}
	}

	static public UISelectOne findSelectOneById(final String componentId) {
		final FacesContext ctx = FacesContext.getCurrentInstance();
		UISelectOne result = null;

		for (final Iterator<UIComponent> i = ctx.getViewRoot().getChildren()
				.iterator(); i.hasNext();) {
			result = getNestedSelectOneComponentById(i.next(), componentId, ctx);
			if (null != result) {
				break;
			}
		}

		return result;

	}

	public static String getHttpRequest() {
		return null;

	}

	public static String getHttpResponse() {
		return null;

	}

	public static String getRemoteAddr() {
		return ((HttpServletRequest) FacesContext.getCurrentInstance()
				.getExternalContext().getRequest()).getRemoteAddr();
	}

	public static String getRemoteUser() {
		return FacesContext.getCurrentInstance().getExternalContext()
				.getRemoteUser();
	}

	static private UISelectOne getNestedSelectOneComponentById(
			final UIComponent component, final String componentId,
			final FacesContext ctx) {
		// System.out.println("Obradjujem: "+ component.getClientId(ctx));
		if (component instanceof UISelectOne
				&& componentId.equals(component.getClientId(ctx))) {
			return (UISelectOne) component;
		}
		UISelectOne result = null;
		for (final Iterator<UIComponent> i = component.getChildren().iterator(); i
				.hasNext();) {
			result = getNestedSelectOneComponentById(i.next(), componentId, ctx);
			if (null != result) {
				break;
			}
		}
		return result;
	}
}
